package com.litchi.tutor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.litchi.tutor.common.entity.Dict;
import com.litchi.tutor.mapper.DictMapper;
import com.litchi.tutor.service.DictService;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xyouzi
 * @date 2021/10/31 12:18
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    DictMapper dictMapper;

    /**
     * 获取字典数据
     * @param type
     * @return
     */
    @Override
    public List<Dict> getDictByType(String type) {
        List<Dict> type1 = dictMapper.selectList(new QueryWrapper<Dict>().like("type", type));
        return type1;
    }

    @Override
    public void createDict(Dict dict) {
        Dict newDict = new Dict();
        BeanUtils.copyProperties(dict, newDict);
        newDict.setDefaultOption(0);
        save(newDict);
    }

    @Override
    public void updateDict(Dict dict) {
        Dict newDict = new Dict();
        BeanUtils.copyProperties(dict, newDict, "default_option");
        update(newDict, new QueryWrapper<Dict>().eq("id", dict.getId()));
    }

    @Override
    public void updateDefaultOption(Integer id, String type) {
        Dict one = getOne(new QueryWrapper<Dict>().eq("id", id).and(wrapper -> wrapper.eq("type", type)));
        if (one != null) {
            List<Dict> list = list(new QueryWrapper<Dict>().eq("type", type));
            Dict dict = list.stream().filter(item -> item.getDefaultOption() == 1).findFirst().orElse(null);
            if (dict != null) {
                if (!dict.getId().equals(id)) {
                    // 要修改的当前数据不是 default_option 为1的数据
                    dict.setDefaultOption(0);
                    update(dict, new QueryWrapper<Dict>().eq("id", dict.getId()));
                    Dict id1 = getOne(new QueryWrapper<Dict>().eq("id", id));
                    id1.setDefaultOption(1);
                    update(id1, new QueryWrapper<Dict>().eq("id", id));
                }
            } else {
                Dict id1 = getOne(new QueryWrapper<Dict>().eq("id", id));
                id1.setDefaultOption(1);
                update(id1, new QueryWrapper<Dict>().eq("id", id));
            }
        }
         else {
            throw new RuntimeException("请输入正确的字典类型和id");
        }
    }
}
